package com.yami.shop.search.common.util;

import com.yami.shop.bean.bo.UserSearchHistoryVO;
import com.yami.shop.bean.model.UserSearchHistory;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Json;
import com.yami.shop.search.common.constant.EsConstant;
import com.yami.shop.search.common.constant.EsIndexEnum;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeRequestBuilder;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @author YXF
 * @date 2021/07/29
 */
@Component
public class EsSearchHotWordUtil {

    private static final Logger log = LoggerFactory.getLogger(EsSearchHotWordUtil.class);

    /**
     * 正常来说普通方法才是属于实体对象（也就是New出来的对象）的，spring注入是在容器中实例化对象，静态变量是无法注入的
     * 所以需要通过构造方法的方式来进行注入，或者使用@PostConstruct注解
     */

    public static void save(UserSearchHistory userSearchHistory) {
        UserSearchHistoryVO userSearchHistoryVO = new UserSearchHistoryVO(userSearchHistory);
        save(userSearchHistoryVO, EsIndexEnum.HOTWORDS.value());
    }

    public static void save(UserSearchHistoryVO userSearchHistoryVO, String esIndex) {
        if (Objects.isNull(userSearchHistoryVO)) {
            return;
        }
        IndexRequest request = new IndexRequest(esIndex)
                .id(userSearchHistoryVO.getHistoryId().toString())
                .source(Objects.requireNonNull(Json.toJsonString(userSearchHistoryVO)), XContentType.JSON);
        EsSearchUtil.save(request);
    }

    public static void delete(String id) {
        // 删除数据
        EsSearchUtil.delete(id, EsIndexEnum.HOTWORDS.value());
    }

    public static void deleteBatch(Collection<String> ids) {
        EsSearchUtil.deleteBatch(ids, EsIndexEnum.HOTWORDS.value(),EsConstant.historyId);
    }


    public static List<String> suggestions(String prefix,int size) {
        SearchRequest request = new SearchRequest(EsIndexEnum.HOTWORDS.value());
        request.source()
                .suggest(new SuggestBuilder().addSuggestion(
                        "suggestions",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .prefix(prefix)
                                .skipDuplicates(true)
                                .size(size)
                ));
       return EsSearchUtil.suggestions(request);
    }
    public static List<String> searchByUserId(String userId,int size) {
        SearchRequest request = new SearchRequest(EsIndexEnum.HOTWORDS.value());
        request.source().query(QueryBuilders.termQuery(EsConstant.userId,userId));
        //分页 from 是分页开始的位置， size 是期望获取的文档总数
        request.source().from(0).size(size);
        //价格升序
        request.source().sort(EsConstant.createTime, SortOrder.DESC);
        List<Map<String,Object>> mapList = EsSearchUtil.searchByUserId(request);
        List<String> list = new ArrayList<>();
        for (Map<String,Object> map:mapList) {
            list.add(map.get(EsConstant.content).toString());
        }
        return list;
    }


    public static void createIndex(String hotwords) {
        try {
            CreateIndexRequest request = new CreateIndexRequest(hotwords);
            request.settings(Settings.builder()
                    .put("index.number_of_shards", 1)
                    .put("index.number_of_replicas", 0));

            XContentBuilder mappingBuilder = XContentFactory.jsonBuilder();
            mappingBuilder.startObject();
            {
                mappingBuilder.startObject("properties");
                {
                    mappingBuilder.startObject("content");
                    {
                        mappingBuilder.field("type", "keyword");
                    }
                    mappingBuilder.endObject();
                    mappingBuilder.startObject("createTime");
                    {
                        mappingBuilder.field("type", "date");
                    }
                    mappingBuilder.endObject();
                    mappingBuilder.startObject("historyId");
                    {
                        mappingBuilder.field("type", "keyword");
                    }
                    mappingBuilder.endObject();
                    mappingBuilder.startObject("source");
                    {
                        mappingBuilder.field("type", "keyword");
                    }
                    mappingBuilder.endObject();
                    mappingBuilder.startObject("userId");
                    {
                        mappingBuilder.field("type", "keyword");
                    }
                    mappingBuilder.endObject();
                    mappingBuilder.startObject("suggestion");
                    {
                        mappingBuilder.field("type", "completion");
                        mappingBuilder.field("analyzer", "ik_max_word");
                    }
                    mappingBuilder.endObject();
                }
                mappingBuilder.endObject();
            }
            mappingBuilder.endObject();
            EsSearchUtil.createIndex(request);
        } catch (IOException e) {
            log.error(e.toString());
            throw new YamiShopBindException("保存es信息异常" + e);
        }
    }
}
